package com.chatplus.application.service.wxmp.handler;

import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.UserEntity;
import com.chatplus.application.domain.entity.account.WechatUserEntity;
import com.chatplus.application.enumeration.WechatUserStatusEnum;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.account.WechatUserService;
import com.chatplus.application.service.wxmp.WeChatMpEventKeyHandler;
import com.chatplus.application.service.wxmp.builder.TextBuilder;
import com.chatplus.application.service.wxmp.impl.WeChatMpService;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;

/**
 * @author chj
 */
public abstract class AbstractHandler implements WxMpMessageHandler {

    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(AbstractHandler.class);


    protected final WeChatMpService weChatMpService;
    protected final WechatUserService wechatUserService;
    protected final UserService userService;

    protected AbstractHandler(WeChatMpService weChatMpService,
                              WechatUserService wechatUserService,
                              UserService userService
    ) {
        this.weChatMpService = weChatMpService;
        this.wechatUserService = wechatUserService;
        this.userService = userService;
    }

    protected WxMpXmlOutMessage handleByEventKey(String eventKey, WechatUserEntity weChatUser, WxMpXmlMessage wxMpXmlMessage) {
        WeChatMpEventKeyHandler weChatMpEventKeyHandler = this.weChatMpService.getHandler(eventKey);
        if (weChatMpEventKeyHandler == null) {
            return new TextBuilder().build("该二维码已过期或发生了其它错误，请重试",
                    wxMpXmlMessage,
                    weChatMpService);
        }
        return weChatMpEventKeyHandler.handle(wxMpXmlMessage, weChatUser);
    }

    public WechatUserEntity handleUser(String appId, String openId, WechatUserStatusEnum wechatUserStatus) {
        try {
            WechatUserEntity weChatUser = this.wechatUserService.getOneByOpenidAndAppId(openId, appId);
            WxMpUser wxMpUser = weChatMpService.getUserService().userInfo(openId);
            String unionId = wxMpUser.getUnionId();
            if (weChatUser == null) {
                weChatUser = new WechatUserEntity();
                weChatUser.setOpenId(openId);
                weChatUser.setAppId(appId);
                UserEntity userEntity = userService.wxOneClickRegister();
                weChatUser.setUserId(userEntity.getId());
            }
            if (StringUtils.isNotEmpty(unionId)) {
                weChatUser.setUnionId(unionId);
            }
            weChatUser.setStatus(wechatUserStatus);
            wechatUserService.saveOrUpdate(weChatUser);
            return weChatUser;
        } catch (Exception e) {
            LOGGER.message("微信用户处理失败")
                    .context("OPENID", openId)
                    .context("appId", appId)
                    .exception(e)
                    .error();
            throw new BadRequestException("微信用户处理失败");
        }
    }
}
